#include <stdio.h>
#include "Hw3Types.h"
#include "Hw3TypesExtended.h"
#include "GlobalVariables.h"
#include "TestFunctions.h"
#include "SyncAndProtectionModule.h"

//Function Declarations
TFace *AddToFacebook(TBox FoundFaceBox);
//End of Function Declarations


TFace *AddToFacebookProtected (TBox *FoundFaceBox) //NEED TO FINISH
{
	DWORD WaitResult;
	BOOL ReleaseResult;
	TFace *AddedFace = NULL;
	
	//check that no one else is adding a new head to the facebook
	WaitResult = WaitForSingleObject( hAddFaceToFacebookMutex, INFINITE ); 
	if ( WaitResult == WAIT_OBJECT_0 ) 
		// add the face to the facebook
		AddedFace = AddToFacebook(*FoundFaceBox);
	else 
	{
		PrintErrorAndTerminate(ERROR_WAITING_FOR_SINGLE_OBJECT);
		return NULL;
	}
	//realease the mutex to allow other threads to add faces to the facebook
	ReleaseResult = ReleaseMutex(hAddFaceToFacebookMutex);
	if ( ReleaseResult == FALSE )
	{
		PrintErrorAndTerminate(ERROR_RELEASING_MUTEX);
		return NULL;
	}
	return AddedFace;
}


void CleanFacebook()
{
	TFace *CurrentFace = FacebookHead;
	TFace *NextFace = NULL;
	while (CurrentFace != NULL)
	{
		// free all elements of the facebook
		NextFace = CurrentFace->NextFace;
		free(CurrentFace);
		CurrentFace = NextFace;
	}	
}


// Internal Functions
TFace *AddToFacebook(TBox FoundFaceBox)
{
	// allocate memory for the new face
	TFace *FaceToAdd= (TFace*)malloc(sizeof(TFace));
	if (FaceToAdd == NULL)
	{
		PrintErrorAndTerminate(ERROR_ALLOCATING_MEMORY);
		return NULL;
	}
	
	// fill in the data
	FaceToAdd->Box = FoundFaceBox;
	FaceToAdd->NextFace = FacebookHead;

	// update the facebook head
	FacebookHead = FaceToAdd;
	#ifdef DEBUG_MODE
		printf("Added face to Facebook. Face is at (%d, %d)\n", FaceToAdd->Box.OriginX, FaceToAdd->Box.OriginY);
		//PrintFacebook();
	#endif
	return FaceToAdd;
}
// End of Internal Functions